Как создать динамическую панель вкладок c во Флаттере? - PullRequest
0 голосов
/ 23 апреля 2020

У меня есть две вкладки, которые построены из класса репозитория. Мне нужно отфильтровать элементы, которые показаны на них в соответствии с национальностями, но элементы отображаются только на первой вкладке. Вторая вкладка ничего не показывает, я думаю, что это связано с Stateful и Stateless.

Как я могу запускать класс репозитория каждый раз, когда я меняю вкладку?

Код ниже касается вкладок и вкладок

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),
      );
    }
  }
}

вкладок и карточек

1 Ответ

1 голос
/ 23 апреля 2020

Вы можете скопировать код вставки и выполнить полный код ниже
Вам необходимо return Container() в else условии и типе возврата Widget не Card
фрагмент кода

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

рабочая демоверсия

enter image description here

полный код

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(),
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...