generics sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({super.key, required this.title}); | |
final String title; | |
@override | |
State<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> with ChangeNotifier { | |
int _index = 0; | |
String _value = '_value'; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
TextButton( | |
onPressed: () { | |
genericsSample('int'); | |
}, | |
child: Text('$_index'), | |
), | |
TextButton( | |
onPressed: () { | |
genericsSample('string'); | |
}, | |
child: Text(_value), | |
), | |
], | |
)), | |
); | |
} | |
// this is generics | |
T genericsSample<T>(String value) { | |
switch (value) { | |
case 'int': | |
_index += 1; | |
_notify(); | |
return _index as T; | |
case 'string': | |
_value = _index.toString(); | |
_notify(); | |
return _value as T; | |
} | |
return 0 as T; | |
} | |
_notify() { | |
setState( | |
() => notifyListeners(), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
2023-05-11.7.16.02.mov