Consumer包
MaterialApp
程式码片段
return MultiProvider( providers: [ ChangeNotifierProvider<Posts>( create: (context) => Posts(), ), ChangeNotifierProvider<Settings>( create: (context) => Settings(darkModeEnabled: true), ), ], child: Consumer<Settings>(builder: (_, settings, child) { return MaterialApp( darkTheme: settings.darkModeEnabled ? ThemeData.dark() : ThemeData.light(), debugShowCheckedModeBanner: false, title: 'Blogy', theme: ThemeData( primaryColor: Colors.deepPurple[900], cursorColor: Colors.deepPurple[900], accentColor: Colors.deepPurple[900], fontFamily: 'Ubuntu', ), home: SplashScreen(), ); }), );
完整的测试代码
import 'package:flutter/material.dart';import 'package:provider/provider.dart';void main() => runApp(MyApp());class Posts extends ChangeNotifier {}class Settings extends ChangeNotifier { bool darkModeEnabled; Settings({this.darkModeEnabled});}class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<Posts>( create: (context) => Posts(), ), ChangeNotifierProvider<Settings>( create: (context) => Settings(darkModeEnabled: true), ), ], child: Consumer<Settings>(builder: (_, settings, child) { return MaterialApp( darkTheme: settings.darkModeEnabled ? ThemeData.dark() : ThemeData.light(), debugShowCheckedModeBanner: false, title: 'Blogy', theme: ThemeData( primaryColor: Colors.deepPurple[900], cursorColor: Colors.deepPurple[900], accentColor: Colors.deepPurple[900], fontFamily: 'Ubuntu', ), home: SplashScreen(), ); }), ); }}class SplashScreen extends StatefulWidget { SplashScreen({Key key}) : super(key: key); //final String title; @override _SplashScreenState createState() => _SplashScreenState();}class _SplashScreenState extends State<SplashScreen> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("test"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)