美文网首页
flutter组件抽离思考

flutter组件抽离思考

作者: 小话001 | 来源:发表于2021-02-03 16:25 被阅读0次

    源代码:

    
    import 'package:flutter/material.dart';
    
    main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title:'app标题' ,
          home: HYHomePage(),
        );
      }
    }
    
    class HYHomePage extends StatefulWidget {
      @override
      _HYHomePageState createState() => _HYHomePageState();
    }
    
    class _HYHomePageState extends State<HYHomePage> {
      ScrollController _controller;
      bool _isShowTop=false;
      @override
      void initState() {
        // TODO: implement initState
        _controller=ScrollController();
        _controller.addListener(() {
          final tempOffSet=_controller.offset>=1000;
          if(tempOffSet!=_isShowTop){
            setState(() {
              _isShowTop=tempOffSet;
            });
          }
        });
        super.initState();
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("标题"),
          ),
          body: ListView.builder(
            itemExtent: 50,
            itemCount: 100,
            controller: _controller,
            itemBuilder: (ctx,index){
               return ListTile(title: Text("第$index条,"),);
            }
            ),
          floatingActionButton: !_isShowTop ? null : FloatingActionButton(
            child: Icon(Icons.arrow_upward),
            onPressed: () {
              _controller.animateTo(0, duration: Duration(milliseconds: 1000), curve: Curves.ease);
            },
          ),
        );
      }
    }
    
    //思考:如果把BodyDemo抽离出来,此处是拿不到_controller的,应该怎么办?
    //class BodyDemo extends StatelessWidget {
    //  @override
    //  Widget build(BuildContext context) {
    //        return ListView.builder(
    //        itemExtent: 50,
    //        itemCount: 100,
    //        controller: _controller,
    //        itemBuilder: (ctx,index){
    //           return ListTile(title: Text("第$index条,"),);
    //        }
    //     );
    //  }
    //}
    
    //class BodyDemo extends StatefulWidget {
    //  @override
    //  _BodyDemoState createState() => _BodyDemoState();
    //}
    //
    //class _BodyDemoState extends State<BodyDemo> {
    //
    //  @override
    //  Widget build(BuildContext context) {
    //    return ListView.builder(
    //        itemExtent: 50,
    //        itemCount: 100,
    //        controller: this._controller,
    //        itemBuilder: (ctx,index){
    //           return ListTile(title: Text("第$index条"),);
    //        }
    //        );
    //  }
    //}
    
    
    思考:怎么拿到_controller?

    相关文章

      网友评论

          本文标题:flutter组件抽离思考

          本文链接:https://www.haomeiwen.com/subject/rshmtltx.html