Передать список для вывода в другом представлении - PullRequest
0 голосов
/ 01 марта 2020

В классе «Категории» у меня есть список элементов. Этот список будет дополнен большим количеством категорий от Firebase. Я хочу прочитать этот список в другом представлении (showCategories.dart) и, таким образом, вывести его в другом представлении (showCategories.dart).

Как передать список в другое представление и получить доступ к элементам списка в этом другом виде?

Код для category.dart

class Categories with ChangeNotifier {
  List<Category> _cats = [
    Category(
      id: 'c1',
      titel: 'Kategorie #1',
      bezeichnung: 'Erste Kategorie',
      gruppe: '1',
    ),
    Category(
      id: 'c2',
      titel: 'Kategorie #2',
      bezeichnung: 'Zweite Kategorie',
      gruppe: '2',
    ),
    Category(
      id: 'c3',
      titel: 'Kategorie #3',
      bezeichnung: 'Dritte Kategorie',
      gruppe: '3',
    ),        
  ];

  List<Category> get cats {
    return [..._cats];
  }

  get length => null;

  Category findById(String id) {
    return _cats.firstWhere(
      (prod) => prod.id == id
    );
  }

  Future<void> fetchAndSetCategories() async {
    const url = 'https://....firebaseio.com/categories.json';
    //print(_cats);
    try {
      final response = await http.get(url);
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      final List<Category> loadedCategories = [];
      extractedData.forEach((catId, catData) {
        loadedCategories.add(Category(
          id: catId,
          titel: catData['titel'],
          bezeichnung: catData['bezeichnung'],
          gruppe: catData['gruppe'],
        ));
      });
      _cats = loadedCategories;

      notifyListeners();

    } catch(error) {
      throw error;
    }
  }
} 

Код для viewCategories.dart

class ViewCategories extends StatefulWidget {

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

class _ViewCategoriesState extends State<ViewCategories> {

  @override
  void initState() {
    Provider.of<Categories>(context, listen: false).fetchAndSetCategories();
    super.initState();
  }
} 

1 Ответ

0 голосов
/ 02 марта 2020

Вы можете скопировать вставить полный код ниже
Вы можете напрямую использовать Consumer для доступа к данным вашей модели

фрагмент кода

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => Categories(),
      child: MyApp(),
    ),
  );
}
...
return Scaffold(
          body: Consumer<Categories>(builder: (context, categoryData, child) {
            print(categoryData.cats.toString());
            return ListView.builder(
                shrinkWrap: true,
                itemCount: categoryData.cats.length,
                itemBuilder: (context, index) => Card(
                      elevation: 3,
                      child: ListTile(
                        title: Text(categoryData.cats[index].titel),
                      ),
                    ));
          }),
        );

рабочая демонстрация

enter image description here

полный код

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import 'dart:convert';

class ViewCategories extends StatefulWidget {
  @override
  _ViewCategoriesState createState() => _ViewCategoriesState();
}

class _ViewCategoriesState extends State<ViewCategories> {
  @override
  void initState() {
    //Provider.of<Categories>(context, listen: false).fetchAndSetCategories();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer<Categories>(builder: (context, categoryData, child) {
        print(categoryData.cats.toString());
        return ListView.builder(
            shrinkWrap: true,
            itemCount: categoryData.cats.length,
            itemBuilder: (context, index) => Card(
                  elevation: 3,
                  child: ListTile(
                    title: Text(categoryData.cats[index].titel),
                  ),
                ));
      }),
    );
  }
}

class Category {
  String id;
  String titel;
  String bezeichnung;
  String gruppe;
  Category({this.id, this.titel, this.bezeichnung, this.gruppe});
}

class Categories with ChangeNotifier {
  List<Category> _cats = [
    Category(
      id: 'c1',
      titel: 'Kategorie #1',
      bezeichnung: 'Erste Kategorie',
      gruppe: '1',
    ),
    Category(
      id: 'c2',
      titel: 'Kategorie #2',
      bezeichnung: 'Zweite Kategorie',
      gruppe: '2',
    ),
    Category(
      id: 'c3',
      titel: 'Kategorie #3',
      bezeichnung: 'Dritte Kategorie',
      gruppe: '3',
    ),
  ];

  List<Category> get cats {
    return [..._cats];
  }

  get length => null;

  Category findById(String id) {
    return _cats.firstWhere((prod) => prod.id == id);
  }

  Future<void> fetchAndSetCategories() async {
    const url = 'https://....firebaseio.com/categories.json';
    //print(_cats);
    try {
      /*final response = await http.get(url);
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      final List<Category> loadedCategories = [];
      extractedData.forEach((catId, catData) {
        loadedCategories.add(Category(
          id: catId,
          titel: catData['titel'],
          bezeichnung: catData['bezeichnung'],
          gruppe: catData['gruppe'],
        ));
      });*/
      final List<Category> loadedCategories = [];
      loadedCategories.add(Category(
        id: "c9",
        titel: 'c9 titel',
        bezeichnung: 'c9 bezeichnung',
        gruppe: 'c9 gruppe',
      ));
      loadedCategories.add(Category(
        id: "c19",
        titel: 'c19 titel',
        bezeichnung: 'c19 bezeichnung',
        gruppe: 'c19 gruppe',
      ));
      _cats = loadedCategories;

      notifyListeners();

    } catch (error) {
      throw error;
    }
  }
}

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => Categories(),
      child: 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;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Demo'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Consumer<Categories>(builder: (context, categoryData, child) {
              print(categoryData.cats.toString());
              return Expanded(
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: categoryData.cats.length,
                    itemBuilder: (context, index) => Card(
                          elevation: 3,
                          child: ListTile(
                            title: Text(categoryData.cats[index].titel),
                          ),
                        )),
              );
            }),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Provider.of<Categories>(context, listen: false).fetchAndSetCategories();
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => ViewCategories()),
            );
          },
          child: Icon(Icons.navigation),
          backgroundColor: Colors.green,
        ));
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...