M
M
mezigar2022-04-19 22:26:59
Dart
mezigar, 2022-04-19 22:26:59

Why is the flutter app crashing?

I'm trying to make the color of the appbar and container change randomly when the switch is switched. I use a provider, but the application crashes, I didn’t google anything sensible

import 'package:flutter/material.dart';

import 'package:provider/provider.dart';
import 'dart:math';

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

class SwitchProvider extends ChangeNotifier {
  bool is_switched = false;

  bool _switch() {
    is_switched = !is_switched;
    notifyListeners();
    return is_switched;
  }
}

class MyApp extends StatelessWidget {
  bool is_changed = true;

  @override
  Widget build(BuildContext context) {
    SwitchProvider _state = Provider.of<SwitchProvider>(context);
    return MaterialApp(
      home: ChangeNotifierProvider<SwitchProvider>.value(
        value: SwitchProvider(),
        child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text(
              "Homework Provider",
            ),
            backgroundColor: Color(
              generateRandomHexColor(),
            ),
          ),
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                color: Color(
                  generateRandomHexColor(),
                ),
                height: 200,
                width: 200,
              ),
              Consumer(
                builder: (context, value, child) => Switch(
                  value: is_changed,
                  onChanged: (is_changed) => _state.is_switched,
                  // onChanged: (bool is_changed) => !is_changed,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Random random = new Random();

int generateRandomHexColor() {
  int length = 6;
  String chars = '0123456789ABCDEF';
  String hex = '';
  while (length-- > 0) hex += chars[(random.nextInt(16)) | 0];
  print(hex);
  return int.parse("0xFF" + hex);
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question