簡體   English   中英

如何在Flutter中創建動態標簽欄?

[英]How to create a dynamic tab bar in Flutter?

我有兩個從存儲庫 class 構建的選項卡。 我需要根據國籍過濾顯示在它們上的項目,但這些項目僅在第一個選項卡上呈現。 第二個選項卡沒有顯示任何內容,我相信它與有狀態和無狀態有關。

每次更改選項卡時,如何運行存儲庫 class?

下面的代碼是關於 Tab 和 TabView

import 'package:flutter/material.dart';
import 'package:flutterbol/models/teams_model.dart';
import 'package:flutterbol/repository/teams_repository.dart';

class TeamsScreen extends StatefulWidget {
  @override
  _TeamsScreenState createState() => _TeamsScreenState();
}

class _TeamsScreenState extends State<TeamsScreen> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: choices.length,
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Tabbed AppBar'),
            bottom: TabBar(
              isScrollable: true,
              tabs: choices.map((Choice choice) {
                return Tab(
                  text: choice.title,
                  icon: Icon(choice.icon),
                );
              }).toList(),
            ),
          ),
          body: TabBarView(
            children: choices.map((Choice choice) {
              return Padding(
                padding: const EdgeInsets.all(16.0),
                child: ChoiceCard(choice: choice),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

class Choice {
  const Choice({this.title, this.icon});

  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'NATIONALS', icon: Icons.flag),
  const Choice(title: 'INTERNATIONALS', icon: Icons.outlined_flag),
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({Key key, this.choice}) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: FutureBuilder<List<TeamsModel>>(
          future: TeamsRepository().findAllAsync(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return buildListView(snapshot.data);
            } else {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
          },
        ));
  }

  ListView buildListView(List<TeamsModel> teams) {
    return ListView.builder(
      itemCount: teams == null ? 0 : teams.length,
      //itemCount: teams.length,
      itemBuilder: (BuildContext ctx, int index) {
        return teamCard(teams[index]);
      },
    );
  }

  Card teamCard(TeamsModel team) {
    if (team.nacionalidade == choice.title) {
      return Card(
        child: Text(team.name),
      );
    }
  }
}

標簽和卡片

您可以在下面復制粘貼運行完整代碼
您需要在else條件下return Container()並且返回類型是Widget而不是Card
代碼片段

  Widget teamCard(TeamsModel team) {
    if (team.nacionalidade == choice.title) {
      return Card(
        child: Text(team.name),
      );
    } else {
      return Container();
    }
  }

工作演示

在此處輸入圖像描述

完整代碼

import 'package:flutter/material.dart';

class TeamsModel {
  String nacionalidade;
  String name;

  TeamsModel(this.name, this.nacionalidade);
}

class TeamsRepository {
  Future<List<TeamsModel>> findAllAsync() {
    return Future.value([
      TeamsModel("a", "NATIONALS"),
      TeamsModel("b", "NATIONALS"),
      TeamsModel("c", "INTERNATIONALS"),
      TeamsModel("d", "INTERNATIONALS")
    ]);
  }
}

class TeamsScreen extends StatefulWidget {
  @override
  _TeamsScreenState createState() => _TeamsScreenState();
}

class _TeamsScreenState extends State<TeamsScreen> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: choices.length,
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Tabbed AppBar'),
            bottom: TabBar(
              isScrollable: true,
              tabs: choices.map((Choice choice) {
                return Tab(
                  text: choice.title,
                  icon: Icon(choice.icon),
                );
              }).toList(),
            ),
          ),
          body: TabBarView(
            children: choices.map((Choice choice) {
              print(choice.title);
              return Padding(
                padding: const EdgeInsets.all(16.0),
                child: ChoiceCard(choice: choice),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

class Choice {
  const Choice({this.title, this.icon});

  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'NATIONALS', icon: Icons.flag),
  const Choice(title: 'INTERNATIONALS', icon: Icons.outlined_flag),
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({Key key, this.choice}) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: FutureBuilder<List<TeamsModel>>(
      future: TeamsRepository().findAllAsync(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return buildListView(snapshot.data);
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    ));
  }

  ListView buildListView(List<TeamsModel> teams) {
    return ListView.builder(
      itemCount: teams == null ? 0 : teams.length,
      //itemCount: teams.length,
      itemBuilder: (BuildContext ctx, int index) {
        return teamCard(teams[index]);
      },
    );
  }

  Widget teamCard(TeamsModel team) {
    if (team.nacionalidade == choice.title) {
      return Card(
        child: Text(team.name),
      );
    } else {
      return Container();
    }
  }
}

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM