Использование виджета Choicechip с приложением Купертино - PullRequest
1 голос
/ 26 октября 2019

Я пытаюсь использовать виджет ChoiceChip в приложении Купертино.

Я нашел это решение https://github.com/flutter/flutter/issues/21872#issuecomment-421508939 на GitHub

CupertinoApp(
  localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
      DefaultMaterialLocalizations.delegate,
      DefaultWidgetsLocalizations.delegate,
  ],
  title: 'Flutter Demo',
  home: new MyHomePage(title: 'Flutter Demo Home Page'),
)

Вот мой код

return CupertinoApp(
  localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
    DefaultWidgetsLocalizations.delegate,
  ],
  home: CupertinoStoreHomePage(),
);
  _buildChoiceList() {
    List<Widget> choices = List();
    widget.reportList.forEach((item) {
      choices.add(Container(
        child: ChoiceChip(
          label: Text(item),
          selected: selectedChoice == item,
          onSelected: (selected) {
            setState(() {
              selectedChoice = item;
              widget.onChoiceSelected(item);
            });
          },
        ),
      ));
    });
    return choices;
  }

, и я получаю эту ошибку

════════ Исключение, обнаруженное библиотекой виджетов ═════════════════════════════════Следующее утверждение было выброшено при создании ChoiceChip (грязный): Виджет «Материал» не найден.

Для виджетов ChoiceChip требуется предок виджета «Материал».

1 Ответ

0 голосов
/ 29 октября 2019

Вам нужен помост в CupertinoStoreHomePage
полный рабочий код и демонстрация, см. Ниже

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

CupertinoApp(
  localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
    DefaultMaterialLocalizations.delegate,
    DefaultWidgetsLocalizations.delegate,
  ],
  home: CupertinoStoreHomePage(
    reportList: ["a", "b"],
    onChoiceSelected: (item) {
      print(item);
    },
  ),
)

enter image description here

полный код

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
        DefaultMaterialLocalizations.delegate,
        DefaultWidgetsLocalizations.delegate,
      ],
      home: CupertinoStoreHomePage(
        reportList: ["a", "b"],
        onChoiceSelected: (item) {
          print(item);
        },
      ),
    );
  }
}

class CupertinoStoreHomePage extends StatefulWidget {
  List<String> reportList;
  Function(String) onChoiceSelected;

  CupertinoStoreHomePage({Key key, this.reportList, this.onChoiceSelected})
      : super(key: key);
  @override
  _CupertinoStoreHomePageState createState() => _CupertinoStoreHomePageState();
}

class _CupertinoStoreHomePageState extends State<CupertinoStoreHomePage> {
  String selectedChoice;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text("demo"),
        ),
        body: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: _buildChoiceList(),
        ));
  }

  _buildChoiceList() {
    List<Widget> choices = List();
    widget.reportList.forEach((item) {
      choices.add(Container(
        child: ChoiceChip(
          label: Text(item),
          selected: selectedChoice == item,
          onSelected: (selected) {
            setState(() {
              selectedChoice = item;
              widget.onChoiceSelected(item);
            });
          },
        ),
      ));
    });
    return choices;
  }
}

Выход

I/flutter (10201): a
I/flutter (10201): b
...