Skip to content

Instantly share code, notes, and snippets.

@dkbast
Created October 26, 2022 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkbast/2a8dcece1146bb0f85d814087f08dec2 to your computer and use it in GitHub Desktop.
Save dkbast/2a8dcece1146bb0f85d814087f08dec2 to your computer and use it in GitHub Desktop.
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Füge ganz oben im WidgetTree den Provider ein
return ChangeNotifierProvider(
create: (_) => CounterProvider(),
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
State<MyHomePage> 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(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
// mit context.watch wird automatisch ein rerender angestoßen wenn sich etwas ändert
// teste einmal context.read und prüfe was dann passiert
'${context.watch<CounterProvider>().count}',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
// hier nutzen wir context.read, da wir nur den Zugriff auf
// die Instanz brauchen aber sich der Button nicht neu bauen muss
onPressed: context.read<CounterProvider>().increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
/// Diese Klasse hält jetzt unseren State
class CounterProvider extends ChangeNotifier {
/// der underscore macht die Variable privat
int _count = 0;
void increment() {
_count++;
// mit notifyListeners teilen wir allen listenern mit dass sich etwas geändert hat
notifyListeners();
}
/// mit dem keyword get definieren wir einen getter - es gibt keine
/// Möglichkeit den count von außen zu überschreiben,
/// die private Variable ist also "sicher" vor unbefugtem Zugriff
int get count => _count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment