В Flutter iconButton - щелчок в appBar, но появляется ошибка - PullRequest
0 голосов
/ 16 декабря 2018

я пытался вызвать диалоговое окно, когда iconButton щелкает в appBar, но появляется ошибка

эта ошибка является постоянной.

Я думаю, что контекст передан в showDialog() есть некоторые проблемы, я не уверен, что импорт 'пакет: flutter / material.dart';import 'package: flutter_colorpicker / flutter_colorpicker.dart';

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

class MyApp extends StatefulWidget {
## Heading ##
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyPortfolioState();
  }
}

class _MyPortfolioState extends State<MyApp> {
  MaterialColor primaryColor = Colors.blue;
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Portfolio',
        theme: new ThemeData(
          primarySwatch: primaryColor,
        ),
        home: Scaffold(
            appBar: AppBar(
                title: Text("Dhruv Agarwal"),
                textTheme: TextTheme(
                    display2: TextStyle(color: Color.fromARGB(1, 0, 0, 0))),
                actions: <Widget>[
              new IconButton(
                icon: Icon(Icons.format_color_text),
                tooltip: 'Change Color',
                onPressed: () {
                  Color pickerColor = primaryColor;
                  changeColor(Color color) {
                    setState(() => primaryColor = color);
                  }
                  showDialog (
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: const Text('Pick a color!'),
                          content: SingleChildScrollView(
                            child: ColorPicker(
                              pickerColor: pickerColor,
                              onColorChanged: changeColor,
                              pickerAreaHeightPercent: 0.8,
                            ),
                          ),
                          actions: <Widget>[
                            FlatButton(
                              child: Text('Got it'),
                              onPressed: () {
                                setState(() => primaryColor = pickerColor);
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      });
                },
              ),
            ])));
  }
}

//
//

Исключение выдается при перезагрузке, которая не обнаружена Локализация материалов.

Launching lib/main.dart on Redmi Note 5 Pro in debug mode...
Initializing gradle...
Resolving dependencies...
Gradle task 'assembleDebug'...
Built build/app/outputs/apk/debug/app-debug.apk.
Installing build/app/outputs/apk/app.apk...
I/zygote64(16669): Do partial code cache collection, code=28KB, data=20KB
I/zygote64(16669): After code cache collection, code=28KB, data=20KB
I/zygote64(16669): Increasing code cache capacity to 128KB
Syncing files to device Redmi Note 5 Pro...
I/flutter (16669): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (16669): The following assertion was thrown while handling a gesture:
I/flutter (16669): No MaterialLocalizations found.
I/flutter (16669): MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
I/flutter (16669): Localizations are used to generate many different messages, labels,and abbreviations which are used
I/flutter (16669): by the material library. 
I/flutter (16669): To introduce a MaterialLocalizations, either use a  MaterialApp at the root of your application to
I/flutter (16669): include them automatically, or add a Localization widget with a MaterialLocalizations delegate.
I/flutter (16669): The specific widget that could not find a MaterialLocalizations ancestor was:
I/flutter (16669):   MyApp
I/flutter (16669): The ancestors of this widget were:
I/flutter (16669):   [root]
I/flutter (16669): 
I/flutter (16669): When the exception was thrown, this was the stack:
I/flutter (16669): #0      debugCheckHasMaterialLocalizations.<anonymous closure> (package:flutter/src/material/debug.dart:124:7)
I/flutter (16669): #1      debugCheckHasMaterialLocalizations (package:flutter/src/material/debug.dart:127:4)
I/flutter (16669): #2      showDialog (package:flutter/src/material/dialog.dart:606:10)
I/flutter (16669): #3      MyApp.build.<anonymous closure> (file:///home/punisher/AndroidStudioProjects/first_app/portfolio/lib/main.dart:32:19)
I/flutter (16669): #4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
I/flutter (16669): #5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
I/flutter (16669): #6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
I/flutter (16669): #7      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
I/flutter (16669): #8      TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:204:7)
I/flutter (16669): #9      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
I/flutter (16669): #10     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:147:20)
I/flutter (16669): #11     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
I/flutter (16669): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
I/flutter (16669): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
I/flutter (16669): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
I/flutter (16669): #15     _invoke1 (dart:ui/hooks.dart:153:13)
I/flutter (16669): #16     _dispatchPointerDataPacket (dart:ui/hooks.dart:107:5)
I/flutter (16669): 
I/flutter (16669): Handler: onTap
I/flutter (16669): Recognizer:
I/flutter (16669):   TapGestureRecognizer#5070d(debugOwner: GestureDetector, state: ready, won arena, finalPosition:
I/flutter (16669):   Offset(354.2, 64.0), sent tap down)
I/flutter (16669): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (16669): Another exception was thrown: No MaterialLocalizations found.

1 Ответ

0 голосов
/ 16 декабря 2018

Некоторые виджеты материалов в вашем дереве требуют настройки локализации, поэтому вместо прямого запуска приложения из StatefulWidget оберните его в MaterialApp.Таким образом, MaterialApp будет иметь ваш виджет в качестве дочернего элемента, а не наоборот.

main() => runApp(
      MaterialApp(
        title: 'ColorPicker test',
        home: MyApp(),
      ),
    );

MaterialApp установит MaterialLocalizations в дереве виджетов, и его дочерние элементы смогут использовать его.

Кстати, ваш код не будет работать, поскольку ColorPicker выбирает из всех возможных цветов, а primarySwatch может быть только MaterialColor с.Вы можете попробовать еще раз, используя материал ColorPicker.Я думаю этот плагин также предоставляет его, вы можете проверить этот тоже .

...