第013例-动态替换widget-(学习Flutter第4天)

在这里插入图片描述
网页地址:网页演示

参考:

  • Flutter动态替换Widget的练习链接

一. 创建项目

flutter create example013_dynamicchange

二. AS打开

三. 添加依赖、放入资源文件

四. 编写代码

main.dart

import 'package:flutter/material.dart';

void main() {
    
    
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
    
    
  @override
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
    
    
  MyHomePage({
    
    Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
    
    
  int _counter = 0;

  Widget title = new Text('another times: 0',);

  static Element findChild(Element e, Widget w) {
    
    
    Element child;
    void visit(Element element) {
    
    
      if (w == element.widget)
        child = element;
      else
        element.visitChildren(visit);
    }
    visit(e);
    return child;
  }


  void _incrementCounter()
  {
    
    
    _counter++;
    print("_incrementCounter()");
    Element e = findChild(context as Element, title);
    if (e != null)
    {
    
    
      title = new Text('another times: $_counter',);
      e.owner.lockState(()
      {
    
    
        e.update(title);
      });
    }

  }

  @override
  Widget build(BuildContext context) {
    
    
   
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      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.headline4,
            ),
            title,
            // title2,
            // container,
            // column,
            Icon(Icons.arrow_back)

          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}


6. 调试运行

AS中先打开Android或者iOS模拟器,点运行按钮。
或在命令行中运行:

flutter run

7. 打包web

flutter build web

源码

https://gitee.com/ruik2080/example-flutter

猜你喜欢

转载自blog.csdn.net/qiang2080/article/details/115196524