gpt4 book ai didi

flutter - 在构建函数之外使用BuildContext

转载 作者:行者123 更新时间:2023-12-03 02:42:33 25 4
gpt4 key购买 nike

我有一个构建可重用它的小部件的函数,在该函数中,我想设置文本主题。我的问题是要做到这一点,我需要访问BuildContext。我能想到的唯一方法是在每个函数调用中将其作为参数传递,但感觉必须有一个更简单的方法。还是这是最好的方法?

这是当前代码:

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

import 'package:snapping_page_scroll/snapping_page_scroll.dart';

void main() => runApp(MaterialApp(
theme: ThemeData(
backgroundColor: Color(0xff121217),
textTheme: TextTheme(
headline: TextStyle(fontSize: 40)
)
),
home: SplashScreen(),
));

class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
loadData();
}

//Simulates loading of data
Future<Timer> loadData() async {
return new Timer(Duration(seconds: 1), onDoneLoading);
}

onDoneLoading() async {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Home()));
}

@override
Widget build(BuildContext context) {
return Container(
color: Color(0xff121217),
child: Padding(
padding: const EdgeInsets.all(20),
child: Image.asset('assets/logo.png'),
),
);
}
}

class Home extends StatelessWidget {

Widget page(text, color, context){
return Container(
color: color,
child: Align(
alignment: Alignment(0, 0.5),
child: Text(text, style: Theme.of(context).textTheme.headline,),
),
);
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: SnappingPageScroll(
children: <Widget>[
page('Page 1', Colors.orange, context),
page('Page 2', Colors.green, context),
],
),
),
);
}
}

最佳答案

您可以使用构建器小部件。 ...
https://api.flutter.dev/flutter/widgets/Builder-class.html

关于flutter - 在构建函数之外使用BuildContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com