This chapter follows the content of the previous chapter, which mainly discussed how to use multiple languages in FLUTTER. This chapter mainly describes how to use providers to manage the state of FLUTTER to achieve page language switch.

  1. Install the provider dependency and introduce the provider in pubspec.yaml.

Provider: ^5.0.0 dev_dependencies: flutter_test: SDK: flutter flutter_localizations: sdk: flutter flutter_intl: enabled: trueCopy the code
  1. Create a provider that stores the Local language

import 'package:flutter/material.dart'; class LocalProvide extends ChangeNotifier { String currentLang = 'en'; setLocalLanguage(curLang) { currentLang = curLang; notifyListeners(); }}Copy the code
  1. To inject the local state of the provider globally, the code in main.dart is as follows

import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_intl/generated/l10n.dart'; import 'package:provider/provider.dart'; import 'package:flutter_intl/provider/local.dart'; void main() { runApp(MultiProvider(providers: [ ChangeNotifierProvider(create: (_) => LocalProvide()), ], child: MyApp())); } ValueChanged<Locale> localeChange; class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> {// new sets the current language // Locale _locale = const Locale('zh', ''); // @override // void initState() { // super.initState(); // localeChange = (locale) { // setState(() { // _locale = locale; / /}); / /}; } // new @override Widget build(BuildContext context) {return Consumer<LocalProvide>( (context, localProvide, child) { return MaterialApp( title: 'project', theme: ThemeData.dark(), debugShowCheckedModeBanner: false, localizationsDelegates: const [ S.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate ], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (BuildContext context) { return Localizations.override( context: context, locale: Locale(localProvide.currentLang, ''), child: Scaffold( appBar: AppBar( title: CenterTitle: true,), body: Center(child: Column(children: [ Container( padding: EdgeInsets.all(30), height: 100, child: Text( S.of(context).app_name, style: TextStyle(fontSize: 30), ), ), InkWell( onTap: () { String curLang = localProvide.currentLang; if (curLang == 'en') { curLang = 'zh'; } else { curLang = 'en'; } Provider.of<LocalProvide>(context, listen: false) .setLocalLanguage(curLang); }, child: Text( S.of(context).toggle_lang, style: TextStyle(fontSize: 30), ), ) ], ), ), ), ); },),); }); }}Copy the code

Well at this time click switch language can realize real-time language switch.