【问题标题】:divide screen into two equal parts in flutter在颤动中将屏幕分成两个相等的部分
【发布时间】:2019-07-22 00:36:46
【问题描述】:

下面是我的屏幕,我正在尝试获取

 body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(child:
            Chewie(
              controller: _chewieController,
            )
            ),
            TabBar(
              labelColor:Colors.black,
              tabs: categoryNames,
            ),
            Expanded(
                child:TabBarView(
                  children: [
                    ImageList()
                  ],
            ),
            ),
          ],
        )
    ),
  ),

但我不知道如何将屏幕划分为多个部分并为它们添加小部件。请帮我解决这个问题。

以上是我迄今为止尝试过的代码。

class ImageList extends StatelessWidget {
  final List<SubContentsDatum>images = [];

  //ImageModel data = new ImageModel();
  //ImageList();

  Widget build(context) {
    fetchSubCategoryContentlist(context, 20);
    print('iamgelist:$images');
    print('imagelistlengthimages:${images.length}');
    return Expanded(
      child: GridView.count(
        shrinkWrap: true,
        childAspectRatio: 2,
        scrollDirection: Axis.vertical,
        crossAxisCount: 2,
        children: new List<Widget>.generate(images.length, (index) {
          return buildImage(images[index], context, index);
        },
        ).toList(),
      ),
    );
  }

  Widget buildImage(SubContentsDatum image, BuildContext context, int index) {
    return SingleChildScrollView(
      padding: EdgeInsets.only(top: 20.0),
      child: Column(
        children: <Widget>[
          new InkResponse(
            child: Image.network(image.thumbnailUrl.replaceAll(
                "onnet-video-platform", "xxxxx")),
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) =>
                  ChewieDemo.fromChewieDemo(subContentsData: images[index],)));
            },
          ),
          Text(image.name,
            style: TextStyle(
                color: Colors.white
            ),
          ),
        ],
      ),
    );
  }

  Future<SubContentModel> fetchSubCategoryContentlist(BuildContext context,
      int value) async {
    String url = "http://xxxx:xx/onnet_api/mediaListByCatId.php";
    var body = Map<String, String>();
    body['publisherid'] = 102.toString();
    body['tag'] = "media";
    body['subtag'] = "list";
    body['catId'] = value.toString();

    http.Response res = await http.post(url, body: body);
    final data = json.decode(res.body);
    var map = Map<String, dynamic>.from(data);
    var subCategoryContentsResponse = SubContentModel.fromJson(map);

    if (res.statusCode == 200) {
      if (subCategoryContentsResponse.status == 1) {
        var subData = data['data'] as List;
        print('subcontentsresponse:$subData');
        for (var model in subData) {
          images.add(new SubContentsDatum.fromJson(model));
        }
        print('playerlengthimages:${images.length}');
      }
    }
  }
}

这是我的图像列表类文件,我尝试了你们所有人所说的,但我没有得到输出。请检查一下这段代码。

【问题讨论】:

  • remove - Expanded( child: GridView.count( 从这里扩展,因为您之前已经定义了它。
  • 谢谢,解决了。还有一个问题,在我的 Imagelist 类中,直到我完成 fetchSubCategoryContentlist() 方法,我不应该执行其余代码,我该如何实现这一点。
  • 还有一个问题,在我的 Imagelist 类中,直到我完成 fetchSubCategoryContentlist() 方法我不应该执行其余代码,我该如何实现这一点
  • 您需要在fetchSubCategoryContentlist 中添加-return 语句,以便将来完成时-它可以呈现数据
  • @anmol.majhail 非常感谢,我解决了我的问题

标签: android ios flutter


【解决方案1】:

您可以使用 - MediaQuery 获取屏幕大小,然后将其除以 2 得到前半部分。

@override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: title,
//        theme: ThemeData.light().copyWith(
//          platform: _platform ?? Theme.of(context).platform,
//        ),
        home: DefaultTabController(
            length: 3,
            child: Scaffold(
//                appBar: AppBar(
//                  title: Text(title),
//                ),
                body: SafeArea(
                    child: Column(children: <Widget>[
                  Container(
                    color: Colors.greenAccent,
                    height: MediaQuery.of(context).size.height / 2.2,  // Also Including Tab-bar height.
//                        child: Chewie(
//                          controller: _chewieController,
//                        ),
                  ),
                  PreferredSize(
                    preferredSize: Size.fromHeight(50.0),
                    child: TabBar(
                      labelColor: Colors.black,
                      tabs: [
                        Tab(
                          text: 'One',
                        ),
                        Tab(
                          text: 'Two',
                        ),
                        Tab(
                          text: 'Three',
                        )
                      ], // list of tabs
                    ),
                  ),
                  //TabBarView(children: [ImageList(),])
                  Expanded(
                    child: TabBarView(
                      children: [
                        Container(
                          color: Colors.deepOrange,
                          child: Center(child: Text('Tab1')),
                        ),
                        Container(
                          color: Colors.red,
                          child: Center(child: Text('Tab2')),
                        ),
                        Container(
                          color: Colors.yellowAccent,
                          child: Center(child: Text('Tab3')),
                        ) // class name
                      ],
                    ),
                  ),
                ])))));
  }

输出:

使用 AppBar - height: MediaQuery.of(context).size.height / 2.5,

GridView.builder 在 - TabBarView

Expanded(
                    child: TabBarView(
                      children: [
                        GridView.builder(
                          itemBuilder: (context, int) {
                            return CircleAvatar(
                              backgroundImage: NetworkImage(
                                  'https://placeimg.com/640/480/any'),
                            );
                          },
                          itemCount: 20,
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3),
                          shrinkWrap: true,
                        ),
                        Container(
                          color: Colors.red,
                          child: Center(child: Text('Tab2')),
                        ),
                        Container(
                          color: Colors.yellowAccent,
                          child: Center(child: Text('Tab3')),
                        ) // class name
                      ],
                    ),
                  ),

获取异步数据 - 使用 - FutureBuilder

    @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      builder: (context,snap){
        if(snap.hasData){
          return Expanded(
            child: GridView.count(
              shrinkWrap: true,
              childAspectRatio: 2,
              scrollDirection: Axis.vertical,
              crossAxisCount: 2,
              children: new List<Widget>.generate(images.length, (index) {
                return buildImage(images[index], context, index);
              },
              ).toList(),
            ),
          );

        }
        return Center(child: CircularProgressIndicator())
      },
      future: fetchSubCategoryContentlist(context, 20),
    );

【讨论】:

  • 实际上在那个 tabbarview 中,我正在尝试编写一个由 gridview 组成的类。每当我尝试这样做时,都会在扩展不正确使用父小部件时显示错误
  • 如果我给出两个或三个文本和图标,我会得到一个输出,但是当我传递类文件时,我遇到了问题
  • 你能在我的问题中看到我更新的代码吗,我试过了,但我没有得到
  • 在那个 imagelist 类中,对于所有选项卡,只有它应该调用的那个类。我不应该为每个选项卡编写代码。
  • @Mounika - 你放置未来 Builder 的地方 - 应该在 build 方法中。
【解决方案2】:

使用 Expanded 小部件可使 Row、Column 或 Flex 的子级展开以填充主轴中的可用空间(例如,水平的 Row 或垂直的 Column)。如果展开多个children,则根据flex factor在它们之间分配可用空间。

https://docs.flutter.io/flutter/widgets/Expanded-class.html

Column(
  children: <Widget>[
    Expanded(
      child: TopWidget()
    ),
    CenterWidget(),
    Expanded(
      child: BottomWidget()
    ),
  ]
)

编辑:这里有完整的源代码

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @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> {

  @override
  Widget build(BuildContext context) {
    return Column(
        children: <Widget>[
          Expanded(
              child: Container(
                color: Colors.green,
              )
          ),
          Container(
              height: 40,
              color: Colors.grey
          ),
          Expanded(
              child: Container(
                color: Colors.blueGrey,
              )
          ),
        ]
    );
  }
}

编辑 2: 和结果

【讨论】:

  • 查看我更新的代码,我尝试了你所说的任何内容,但它显示父小部件的使用不正确
  • 我的代码没有任何问题。我测试了它。查看更新代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 2015-09-02
相关资源
最近更新 更多