栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Flutter-如何将用户数据传递到所有视图

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Flutter-如何将用户数据传递到所有视图

我建议进一步调查继承的小部件。下面的代码显示了如何在异步更新数据时使用它们:

import 'dart:convert';import 'package:flutter/material.dart';import 'package:http/http.dart' as http;void main() {  runApp(new MaterialApp(      title: 'Inherited Widgets Demo',      theme: new ThemeData(        primarySwatch: Colors.blue,      ),      home: new Scaffold(          appBar: new AppBar( title: new Text('Inherited Widget Example'),          ),          body: new NamePage())));}// Inherited widget for managing a nameclass NameInheritedWidget extends InheritedWidget {  const NameInheritedWidget({    Key key,    this.name,    Widget child}) : super(key: key, child: child);  final String name;  @override  bool updateShouldNotify(NameInheritedWidget old) {    print('In updateShouldNotify');    return name != old.name;  }  static NameInheritedWidget of(BuildContext context) {    // You could also just directly return the name here    // as there's only one field    return context.inheritFromWidgetOfExactType(NameInheritedWidget);  }}// Stateful widget for managing name dataclass NamePage extends StatefulWidget {  @override  _NamePageState createState() => new _NamePageState();}// State for managing fetching name data over HTTPclass _NamePageState extends State<NamePage> {  String name = 'Placeholder';  // Fetch a name asynchonously over HTTP  _get() async {    var res = await http.get('https://jsonplaceholder.typipre.com/users');    var name = json.depre(res.body)[0]['name'];    setState(() => this.name = name);   }  @override  void initState() {    super.initState();    _get();  }  @override  Widget build(BuildContext context) {    return new NameInheritedWidget(      name: name,      child: const IntermediateWidget()    );  }}// Intermediate widget to show how inherited widgets// can propagate changes down the widget treeclass IntermediateWidget extends StatelessWidget {  // Using a const constructor makes the widget cacheable  const IntermediateWidget();  @override  Widget build(BuildContext context) {    return new Center(      child: new Padding(        padding: new EdgeInsets.all(10.0),        child: const NameWidget()));  }}class NameWidget extends StatelessWidget {  const NameWidget();  @override  Widget build(BuildContext context) {    final inheritedWidget = NameInheritedWidget.of(context);    return new Text(      inheritedWidget.name,      style: Theme.of(context).textTheme.display1,    );  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/387586.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号