How do I set the image for a switch button in flutter using the activeThumbImage property? I am a little confused on how to set the ImageProvider value for this property? Is there any example that I could look at that implements the activeThumbImage property of the Switch widget?
You can use an AssetImage or NetworkImage to get an ImageProvider that is suitable for use as an activeThumbImage. Learn more about asset images in the Adding Assets and Images in Flutter tutorial.
Here is some example code that draws the above Switch:
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
MyHomePageState createState() => new MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
bool _enabled;
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Switch(
value: _enabled,
onChanged: (bool value) {
setState(() {
_enabled = value;
});
},
activeThumbImage: new NetworkImage('https://lists.gnu.org/archive/html/emacs-devel/2015-10/pngR9b4lzUy39.png'),
inactiveThumbImage: new NetworkImage('http://wolfrosch.com/_img/works/goodies/icon/vim#2x'),
),
)
);
}
}
void main() {
runApp(new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.deepPurple,
),
home: new MyHomePage(),
));
}
Here is my code.
class ToggleButtonScreen extends StatefulWidget {
#override
_ToggleButtonScreenState createState() => _ToggleButtonScreenState();
}
class _ToggleButtonScreenState extends State<ToggleButtonScreen> {
bool _value = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: _value ? AssetImage("images/cnw.png") : AssetImage("images/cnw.png"),
fit: BoxFit.cover,
),
),
child: Padding(
padding: EdgeInsets.all(AppDimens.EDGE_REGULAR),
child: Column(
children: [
_normalToggleButton(),
],
),
),
),
),
),
);
}
Widget _normalToggleButton () {
return Container(
child: Transform.scale(
scale: 2.0,
child: Switch(
activeColor : Colors.greenAccent,
inactiveThumbColor: Colors.redAccent,
value: _value,
activeThumbImage: AssetImage("images/cnw.png"),
inactiveThumbImage : AssetImage("images/simple_interest.png"),
onChanged: (bool value){
setState(() {
_value = value;
});
},
),
),
);
}
}
pubspec.yaml
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_inappwebview: ^5.3.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter_launcher_icons: "^0.8.0"
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/icon/icon.png"
assets:
- assets/icon/google.png
main.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
class MyChromeSafariBrowser extends ChromeSafariBrowser {
#override
void onOpened() {
print("ChromeSafari browser opened");
}
#override
void onCompletedInitialLoad() {
print("ChromeSafari browser initial load completed");
}
#override
void onClosed() {
print("ChromeSafari browser closed");
}
}
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isAndroid) {
await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
}
runApp(MaterialApp(home: MyApp(), theme: new ThemeData(scaffoldBackgroundColor: const Color(0xFFA7A5A5)),
debugShowCheckedModeBanner: false));
}
class MyApp extends StatefulWidget {
final ChromeSafariBrowser browser = new MyChromeSafariBrowser();
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Image Button"),
),
body:
SingleChildScrollView(
scrollDirection: Axis.vertical,
child:
Column(children: <Widget>[
Container(
// padding: EdgeInsets.all(50),
alignment: Alignment.center,
child: IconButton(
icon: Image.asset('assets/icon/Amazon_icon.png'),
iconSize: 50,
color: Colors.green,
splashColor: Colors.purple,
onPressed: () async {
await widget.browser.open(
url: Uri.parse("https://www.amazon.in/?&_encoding=UTF8&tag=bappasaikh-21&linkCode=ur2&linkId=e3b009b026920c3cfdd6185fadfb7e67&camp=3638&creative=24630"),
options: ChromeSafariBrowserClassOptions(
android: AndroidChromeCustomTabsOptions(
addDefaultShareMenuItem: false,),
ios: IOSSafariOptions(barCollapsingEnabled: true)));
},
),
),
]),
),
);
}
}
Related
I am new to Flutter and went on to do the codelabs - first flutter app
Since I'm learning Flutter to develop mobile apps, this tutorials use of NavigationRail isn't too good looking on a phone. I tried to switch it out for a BottomNavigationBar. When changing the background color of the navbar I noticed it doesnt expand to use the full screen. Is it always like this, or is there something making it display it this way in the code?Could'nt find any useful information about this case.
Is it possible to make the green background cover the, here black, area at the bottom of the screen?
Area under bar, white when debugging on real device, here it is black
The final code from the tutorial is poorly adjusted to:
import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyAppState(),
child: MaterialApp(
title: 'Namer App',
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
),
home: MyHomePage(),
),
);
}
}
class MyAppState extends ChangeNotifier {
var current = WordPair.random();
void getNext() {
current = WordPair.random();
notifyListeners();
}
var favorites = <WordPair>[];
void toggleFavorite() {
if (favorites.contains(current)) {
favorites.remove(current);
} else {
favorites.add(current);
}
notifyListeners();
}
}
class MyHomePage extends StatefulWidget {
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var selectedIndex = 0;
#override
Widget build(BuildContext context) {
Widget page;
switch(selectedIndex){
case 0:
page = GeneratorPage();
break;
case 1:
page = FavoritesPage();
break;
default:
throw UnimplementedError('no widget for $selectedIndex');
}
return LayoutBuilder(
builder: (context, constraints) {
return Scaffold(
body: Center(
child: page,
),
bottomNavigationBar: BottomNavigationBar (
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
label: 'Favorites',
),
],
currentIndex: selectedIndex,
onTap: _onItemTapped,
backgroundColor: Theme.of(context).colorScheme.secondaryContainer,
elevation: 0.0,
),
);
}
);
}
void _onItemTapped(int index){
setState(() {
selectedIndex = index;
});
}
}
class FavoritesPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
var appState = context.watch<MyAppState>();
if (appState.favorites.isEmpty) {
return Center(
child: Text('No favorites yet.'),
);
}
return ListView(
children: [
Padding(
padding: const EdgeInsets.all(20),
child: Text('You have '
'${appState.favorites.length} favorites:'),
),
for (var pair in appState.favorites)
ListTile(
leading: Icon(Icons.favorite),
title: Text(pair.asLowerCase),
),
],
);
}
}
class GeneratorPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
var appState = context.watch<MyAppState>();
var pair = appState.current;
IconData icon;
if (appState.favorites.contains(pair)) {
icon = Icons.favorite;
} else {
icon = Icons.favorite_border;
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
BigCard(pair: pair),
SizedBox(height: 10),
Row(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton.icon(
onPressed: () {
appState.toggleFavorite();
},
icon: Icon(icon),
label: Text('Like'),
),
SizedBox(width: 10),
ElevatedButton(
onPressed: () {
appState.getNext();
},
child: Text('Next'),
),
],
),
],
),
);
}
}
class BigCard extends StatelessWidget {
const BigCard({
Key? key,
required this.pair,
}) : super(key: key);
final WordPair pair;
#override
Widget build(BuildContext context) {
var theme = Theme.of(context);
var style = theme.textTheme.displayMedium!.copyWith(
color: theme.colorScheme.onPrimary,
);
return Card(
color: theme.colorScheme.primary,
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(20),
child: Text(pair.asLowerCase, style: style),
),
);
}
}
Tried changing elevation to 0.0, expandbody and what not. Nothing seems to be working here?
You can use SystemUiOverlayStyle class
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light
.copyWith(systemNavigationBarColor: Colors.greenAccent));
super.initState();
}
Am New in Flutter, Now am trying to add ModalBottomSheet with some textfields and whenever i try to tap on another textField then value got disappeared automatically.
Here is my new_user.dart file
import 'package:flutter/material.dart';
class newUsers extends StatelessWidget {
var nameInputController = TextEditingController();
var marksInputController = TextEditingController();
Function? addNewUser;
newUsers(this.addNewUser);
void submitData() {
print(nameInputController.text);
if (nameInputController.text.isEmpty || marksInputController.text.isEmpty) {
return;
}
addNewUser!(
nameInputController.text, double.parse(marksInputController.text));
}
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
TextField(
decoration: InputDecoration(labelText: "Name"),
controller: nameInputController,
),
TextField(
decoration: InputDecoration(labelText: "Marks"),
controller: marksInputController,
keyboardType: TextInputType.number,
),
ElevatedButton(
onPressed: submitData,
child: Text('Add User Details'),
),
],
),
);
}
}
Home.dart
import 'package:expense_manager/widgets/new_users.dart';
import 'package:expense_manager/widgets/users.dart';
import 'package:expense_manager/widgets/users_list.dart';
import 'models/users.dart';
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<User> users = [
User(id: 1, name: 'himanshurahi', marks: 44.5, createdAt: DateTime.now()),
];
void addNewUser(String name, double marks) {
var newUser =
User(id: 1, name: name, marks: marks, createdAt: DateTime.now());
setState(() {
users.add(newUser);
});
}
#override
Widget build(BuildContext context) {
void addNewUserWithSheet(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (btx) {
return newUsers(addNewUser);
},
);
}
return Scaffold(
appBar: AppBar(
title: Text('my App'),
actions: [
IconButton(
onPressed: () => addNewUserWithSheet(context),
icon: Icon(Icons.add))
],
),
floatingActionButton: FloatingActionButton(
onPressed: () => addNewUserWithSheet(context),
child: Icon(Icons.add)),
body: Container(
child: Column(
children: [
Container(
width: double.infinity,
height: 100,
child: Card(
color: Colors.blueAccent,
child: Text("Chart"),
),
),
newUsers(addNewUser),
usersList(users)
],
),
));
}
}
Here i have added addNewUserWithSheet method to add bottom sheet.
here is main.dart file (if need)
import 'package:expense_manager/home.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
Thanx in advance :)
Ahhh I Basically solved it by using Stateful Widget.
I am using the date_picker_timeline widget and I wanted the date picker to jump to a specific date when I pressed the floating action button. But it's not working as intended. Here is my code.
main.dart
import 'package:flutter/material.dart';
import 'package:date_picker_timeline/date_picker_timeline.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Date Picker"),
),
body: Center(
child: Column(
children: [datePickerMethod()],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
//This is not jumping to the given date
DatePickerController().animateToDate(DateTime(2021, 10, 10));
},
child: Icon(Icons.add),
),
);
}
}
DatePicker datePickerMethod() {
return DatePicker(
DateTime.now(),
initialSelectedDate: DateTime.now(),
selectionColor: Colors.blueAccent,
selectedTextColor: Colors.white,
);
}
pubspec.yaml
name: date_picker_demo
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
date_picker_timeline: ^1.2.3
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
Answered
import 'package:flutter/material.dart';
import 'package:date_picker_timeline/date_picker_timeline.dart';
void main() {
runApp(MyApp());
}
DatePickerController dp = DatePickerController();
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Date Picker"),
),
body: Center(
child: Column(
children: [datePickerMethod()],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
//Fixed
dp.animateToDate(DateTime(2021, 10, 10));
},
child: Icon(Icons.add),
),
);
}
}
DatePicker datePickerMethod() {
return DatePicker(
DateTime.now(),
controller: dp,
initialSelectedDate: DateTime.now(),
selectionColor: Colors.blueAccent,
selectedTextColor: Colors.white,
);
}
I try to use a QR Code Scanner from qr_code_scanner in conjunction with a Webview component webview_flutter.
Everything works fine on iOS but on Android devices it doesn't work, the QR scanner doesn't show and I get a repeated console print.
D/mali_winsys(30667): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
I've tried this on two Android devices (Android 10, v29 and Android 7, v24) with same results.
Below is a minimal app that reproduce the issue. It requires the following dependencies:
qr_code_scanner: ^0.3.5
webview_flutter: ^2.0.2
The code below shows a full-screen webview with a button on-top. Press the button and the QR scanner will/should show up...
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _showQr = false;
#override
void initState() {
super.initState();
// Enable hybrid composition.
if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}
void closeQr() {
setState(() {
_showQr = false;
});
}
#override
Widget build(BuildContext context) {
return Stack(
children: [
Stack(
children: [
WebView(
initialUrl: 'https://flutter.dev',
),
Center(
child: TextButton(
onPressed: () {
setState(() {
_showQr = !_showQr;
});
},
child: Text('Show QR Scanner'),
style: TextButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors.teal,
onSurface: Colors.grey,
),
),
),
],
),
Center(
child: (_showQr) ? QRWidget(onClose: closeQr) : null,
),
],
);
}
}
class QRWidget extends StatefulWidget {
const QRWidget({
Key key,
this.onClose,
}) : super(key: key);
final Function onClose;
#override
State<StatefulWidget> createState() => _QRWidgetState();
}
class _QRWidgetState extends State<QRWidget> {
Barcode result;
QRViewController controller;
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
// In order to get hot reload to work we need to pause the camera if the platform
// is android, or resume the camera if the platform is iOS.
#override
void reassemble() {
super.reassemble();
if (Platform.isAndroid) {
controller.pauseCamera();
}
controller.resumeCamera();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
_buildQrView(context),
Container(
alignment: Alignment.bottomCenter,
padding: EdgeInsets.only(bottom: 60.0),
child: Row(
children: <Widget>[
Expanded(
child: RawMaterialButton(
onPressed: () {
setState(() {
widget.onClose();
});
},
elevation: 2.0,
fillColor: Colors.white,
child: Icon(
Icons.close_sharp,
color: Color(0xff459d44),
size: 40.0,
),
padding: EdgeInsets.all(8.0),
shape: CircleBorder(),
),
),
],
),
)
],
),
);
}
Widget _buildQrView(BuildContext context) {
// For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
var scanArea = (MediaQuery.of(context).size.width < 400 ||
MediaQuery.of(context).size.height < 400)
? 150.0
: 300.0;
// To ensure the Scanner view is properly sizes after rotation
// we need to listen for Flutter SizeChanged notification and update controller
return QRView(
key: qrKey,
onQRViewCreated: _onQRViewCreated,
overlay: QrScannerOverlayShape(
borderColor: Color(0xff459d44),
borderRadius: 10,
borderLength: 30,
borderWidth: 10,
cutOutSize: scanArea),
);
}
void _onQRViewCreated(QRViewController controller) {
setState(() {
this.controller = controller;
});
controller.scannedDataStream.listen((scanData) {
setState(() {
result = scanData;
});
});
}
#override
void dispose() {
controller?.dispose();
super.dispose();
}
}
Why doesn't it work on Android?
did you add the permission in AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
if its webview, why dont you use flutter_inappwebview . Its good to use and has a lot of additional features you may want later. it still needs permission on androidmanifest. Following is the example if you decide to choose flutter_inappwebview.
class _HomePageState extends State<HomePage> {
InAppWebViewController webView;
String url = "";
#override
void initState(){
checkPermissions();
super.initState();
}
#override
void dispose() {
super.dispose();
}
checkPermissions() async{
await [
Permission.camera,
Permission.storage,
].request();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Container(
child: Column(children: <Widget>[
Expanded(
child: Container(
child: InAppWebView(
initialUrl: 'https://flutter.dev',
initialHeaders: {},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
)
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {
setState(() {
this.url = url;
});
},
onLoadStop: (InAppWebViewController controller, String url) async {
setState(() {
this.url = url;
});
},
/// this is the important one to pass the permission
androidOnPermissionRequest: (InAppWebViewController controller, String origin, List<String> resources) async {
return PermissionRequestResponse(resources: resources, action: PermissionRequestResponseAction.GRANT);
},
),
),
),
])
),
),
);
}
}
dont forget to add this permission_handler in your pubspec.yaml
I want to intercept the back-button of the soft keyboard in flutter. So when I want to close the keyboard by pressing the back-button I want an additional function to be called.
How can I do that?
Keyboard Back button
you can use the keyboard_visibility package to achieve this.
Working Example
the following code displays a SnackBar once the keyboard is dismissed.
import 'package:flutter/material.dart';
import 'package:keyboard_visibility/keyboard_visibility.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GlobalKey<ScaffoldState> _key;
#override
void initState() {
super.initState();
_key = GlobalKey<ScaffoldState>();
KeyboardVisibilityNotification().addNewListener(
onHide: () {
_key.currentState.showSnackBar(
SnackBar(
content: Text("Keyboard closed"),
),
);
},
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _key,
body: Center(
child: TextField(),
),
),
);
}
}
you can use the https://pub.dev/packages/flutter_keyboard_visibility package to achieve this.
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_keyboard_visibility_example/keyboard_dismiss_demo.dart';
import 'package:flutter_keyboard_visibility_example/provider_demo.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Demo(),
);
}
}
class Demo extends StatelessWidget {
#override
Widget build(BuildContext context) {
return KeyboardDismissOnTap(
child: Scaffold(
appBar: AppBar(
title: Text('Keyboard Visibility Example'),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProviderDemo()),
);
},
child: Text('Provider Demo'),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => KeyboardDismissDemo()),
);
},
child: Text('KeyboardDismiss Demo'),
),
Spacer(),
TextField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Input box for keyboard test',
),
),
Container(height: 60.0),
KeyboardVisibilityBuilder(builder: (context, visible) {
return Text(
'The keyboard is: ${visible ? 'VISIBLE' : 'NOT VISIBLE'}',
);
}),
Spacer(),
],
),
),
),
),
);
}
}