Package address

Pub. Dev/packages/pr…

1. Download first

Dependencies: Flutter: SDK: flutter provider: ^4.0.1Copy the code

2. Introduce it where it is used

import 'package:provider/provider.dart';
Copy the code

3. Top-level package, routine of general state management tools

There are two methods that do the same thing: use the provider method written by reference

class ThemeState with ChangeNotifier{ int _currentIndex = 0123; Void changeThemeData(index) {// Change the variable's method _currentIndex = index; notifyListeners(); } get currentIndex => _currentIndex; / / 3}Copy the code
  • A can be obtained by importing it directly into main
// void main() => runApp(
//       MultiProvider(
//         providers: [
//           ChangeNotifierProvider<ThemeState>.value(
//               value: ThemeState()), 
//         ],
//         child: MyApp(),
//       ),
//     );

Copy the code
  • Get it from the Widget you useProvider.of<ThemeState>(context).currentIndex;
  • B wrap it with a Wrapper
void main() => runApp(Wrapper(child: MyApp())); class Wrapper extends StatelessWidget { final Widget child; Wrapper({this.child}); @override Widget build(BuildContext context) {final initThemeData = ThemeData(// initial theme primaryColor: colors.blue,);returnMultiProvider( providers: [ ChangeNotifierProvider<ThemeState>.value( value: ThemeState(),), // language package CurrentIndex], child: child,); } } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) {returnConsumer<ThemeState>(Builder: (_, state, __) => MaterialApp(title: state.currentIndex,// Use currentIndex theme: ThemeData(primaryColor: Colors.pink), home: MyHomePage(title:'Flutter Demo Home Page'))); }}Copy the code

4. Call it somewhere else, of course, before using the method you wrote

onTap: (){
    Provider.of<ThemeState>(context,listen: false).changeThemeData(2);
},
Copy the code

5. Create a file whose theme is theme

/** * theme options */ import'package:flutter/material.dart';

final ThemeData themeDataRed = new ThemeData(
  primaryColor: Colors.red,
);
final ThemeData themeDataPink = new ThemeData(
  primaryColor: Colors.pink,
);
final ThemeData themeDataPurple = new ThemeData(
  primaryColor: Colors.purple,
);
final ThemeData themeDataBlack = new ThemeData(
  primaryColor: Colors.black,
);
List themeDataList = [
  themeDataRed,
  themeDataPink,
  themeDataPurple,
  themeDataBlack
];
Copy the code
  • Set it in Miantheme:themeDataList[state.themeData],
  • When changing a theme, you only need to pass in the subscript of the theme color

internationalization

1. Install dependency internationalization plug-in and INTL translation

dependencies: # libraries depend on. flutter_localizations:# international
    sdk: flutter

dev_dependencies:
   #... Omit extraneous termIntl_translation: ^ 0.17.2Copy the code

2. Create the lang.dart file and create the CjmLocalozitions method

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class CjmLocalozitions {
  static CjmLocalozitions of(BuildContext context) {
    return Localizations.of<CjmLocalozitions>(context, CjmLocalozitions);
  }

  String get title =>Intl.message('hello', name: 'title', desc: 'demo localizations');
  
  String greet(String name) => Intl.message(
        'hello $name',
        name: 'greet',
        desc: 'greet someone',
        args: [name],
      );
}

Copy the code

3. Generate an ARB file

Flutter pub pub run intl_translation:extract_to_arb --output-dir=lib/i18n lib/i18n/lang.dart --output-dir// Location of the output file Lib /i18n/lang.dart // We created the location of the lang // when successful we will generate an ARB file copy the arB file and change the text inside to the language you want to nationalizeCopy the code
{
  "@@last_modified": "The 2020-01-16 T10:53:50. 834970"."title": "Hello"."@title": {
    "description": "This is a description."."type": "text"."placeholders": {}},"greet": "Hello {name}"."@greet": {
    "description": "Operate what?"."type": "text"."placeholders": {
      "name": {}}}} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * {"@@last_modified": "The 2020-01-16 T10:53:50. 834970"."title": "Oh, dear.."@title": {
    "description": "demo localizations"."type": "text"."placeholders": {}},"greet": "Kohlview | opinion | opinion | opinion}"."@greet": {
    "description": "greet someone"."type": "text"."placeholders": {
      "name": {}}}}Copy the code

4. Generate THE DART code and generate the DART file according to arB:

flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/i18n/intl --no-use-deferred-loading Dart lib/i18n/intl_*. Arb --output-dir// Output location lib/i18n/lang.dart //CjmLocalozitions file location // Dart file location will be generated if the dart file is successfully generatedCopy the code

5. Modify the lang.dart file

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'messages_all.dart';

class CjmLocalozitions {
  static CjmLocalozitions of(BuildContext context) {
    returnLocalizations.of<CjmLocalozitions>(context, CjmLocalozitions); } / / new static Future < CjmLocalozitions > load (Locale Locale) {final String name = Locale. The countryCode. IsEmpty? locale.languageCode : locale.toString(); final String localeName = Intl.canonicalizedLocale(name); / / 2return initializeMessages(localeName).then((b) {
      Intl.defaultLocale = localeName;
      return new CjmLocalozitions();
    });
  }

  String get title =>
      Intl.message('hello', name: 'title', desc: 'demo localizations');
  String greet(String name) => Intl.message(
        'hello $name',
        name: 'greet',
        desc: 'greet someone', args: [name], ); } / / new Locale proxy class class DemoLocalizationsDelegate extends LocalizationsDelegate < CjmLocalozitions > {const DemoLocalizationsDelegate(); local@override bool isSupported(Locale Locale) {return true;
    // returnlanguages.contains(locale.languageCode); Override Future<CjmLocalozitions> load(Locale Locale) {//3returnCjmLocalozitions.load(locale); } / / when Localizations Widget to build, is called the load reload Locale resources. @ override bool shouldReload DemoLocalizationsDelegate (old) = >false;
}


Copy the code

6. Import files

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:test1/lang/lang.dart';
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Consumer2<ThemeState, LocaleState>(
        builder: (_, themeState, localeState, __) => MaterialApp(
            locale: Locale('en'.'US'// Set the current language environment localizationsDelegates: [/ / localization of the proxy class DemoLocalizationsDelegate (), GlobalMaterialLocalizations. Delegate, GlobalWidgetsLocalizations. Delegate, DemoLocalizationsDelegate(), ], supportedLocales: [ localeState.locale ] title:'321231231',
            theme: themeDataList[themeState.themeData],
        ));
  }
Copy the code

Provider defines the method to switch languages


import 'package:flutter/material.dart'; class LocaleState extends ChangeNotifier{ Locale _locale; / / language LocaleState (enclosing _locale); factory LocaleState.zh()=> LocaleState(Locale('zh'.'CH'));

  factory LocaleState.en()=>
      LocaleState(Locale('en'.'US')); void changeLocaleState(LocaleState state){ _locale=state.locale; notifyListeners(); } Locale get locale => _locale; // get the language}Copy the code

8. Dynamically switch languages

 Locale myLocale = Localizations.localeOf(context);
 
 
 void _incrementCounter(myLocale) {
    print(myLocale.toString());
    if (myLocale.toString() == "en_US") {
        Provider.of<LocaleState>(context, listen: false)
            .changeLocaleState(LocaleState.zh());
    } else {
        Provider.of<LocaleState>(context, listen: false) .changeLocaleState(LocaleState.en()); }}Copy the code
  • Get the local locale

Locale myLocale = Localizations.localeOf(context);

  • For details about other status management tools, see

Juejin. Cn/post / 684490…