我试图在动态范围内实现动态主题。我尝试了以下一些教程和文档。最后,我了解到它将涉及到使用InheritedWidget,因此我尝试从Flutter文档以及此处进行研究。
Flutter: How to correctly use an Inherited Widget?
所以我停留在两个地方。其中之一是如何在MyAppState中更改ThemeData,以及如何在构建MaterialApp时访问该主题数据
还有另外一件事,我必须在哪里使用MyApp.of(context),我在某处尝试了此语句,但这会导致错误
获取器“数据”在null上被调用。
我试图从任何位于MaterialApp内部深处的小部件动态更改ThemeData
我尝试过的是:
import 'package:flutter/material.dart';
void main() => runApp(MainApp());
class _MyInherited extends InheritedWidget {
final MyAppState data;
_MyInherited({Key key, this.data, Widget child})
: super(key: key, child: child);
@override
bool updateShouldNotify(_MyInherited old) {
return true;
}
}
class MyApp extends StatefulWidget {
Widget child;
MyApp({this.child});
@override
State<StatefulWidget> createState() {
return MyAppState();
}
static MyAppState of(BuildContext context) {
return (context.inheritFromWidgetOfExactType(_MyInherited) as _MyInherited)
.data;
}
}
class MyAppState extends State<MyApp> {
ThemeData _myField;
// only expose a getter to prevent bad usage
ThemeData get myField => _myField;
void onMyFieldChange(ThemeData newValue) {
setState(() {
_myField = newValue;
});
}
@override
Widget build(BuildContext context) {
return new _MyInherited(
data: this,
child: widget.child,
);
}
}
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MyApp(
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(primaryColor: Color(0xFFFFFF).withAlpha(0xFF);), //This is the themeData which I have to change from any widget inside MaterialApp
home: Container(height: 200, width: 200, color: Colors.green)
),
);
}
}
我应该怎么做?