Flutter: Yellow Lines Under Text - android

I understand that I do not have a Scaffolding around my text but I'm brand new to flutter and can't seem to work out how to add scaffolding to my text. My code is below:
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test Bench',
home: new Container(
decoration: BoxDecoration(color: Colors.pinkAccent),
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Text(
"Hello, World",
style: TextStyle(
fontSize: 60.0,
fontWeight: FontWeight.bold,
fontFamily: 'Oswald',
color: Colors.black),
),
),
),
);
}
}

You can check by following code. Also refer
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test Bench',
home: Scaffold(
body: new Container(
decoration: BoxDecoration(color: Colors.pinkAccent),
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Text(
"Hello, World",
style: TextStyle(
fontSize: 60.0,
fontWeight: FontWeight.bold,
fontFamily: 'Oswald',
color: Colors.black),
),
),
),
),
);
}
}

I think you need a explanation for this:
Always uses Scaffold (generally better) or any other component that provides material theme like a simple Material widget
remove yellow line text

We can remove yellow lines by adding the Parent widget as "Material" or use "Scaffold"
return MaterialApp(
home: Scaffold(
body: Container(
child: SingleChildScrollView(child: Text('Test')),
),
),
);

Related

Beginner Help Required - BottomNavBar

I am just learning and can't wrap my head around something.
I am building a simple app but the app requires the first thing shown is a splash screen of some sorts.
Upon tapping the only button on the SplashScreen, ideally it would load the rest of the app however I also want my app inside to work around a bottomNavBar.
I have done the Bottom Navigation Bar on my own and it works so I can cycle between my pages, but my main.dart is pointing towards my Splash_Screen. Where as in the Nav model I am using, main points to the Nav.dart file.
How do I get my app to launch in this sequence: Splash_Screen --> when buttom tapped --> go inside where Bottom Navigation Bar will be leading to it's respective 3 pages.
Thanks in advance.
EDIT: CODE
main.dart
import 'package:flutter/material.dart';
import 'package:offroad/screens/splash_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SplashScreen(),
);
}
}
SplashScreen.dart
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:offroad/screens/home_screen.dart';
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
Color mainColor = Color(0xFFF1330A);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/splash.jpg'),
fit: BoxFit.cover,
),
),
child: Container(
color: Colors.black54,
child: Stack(
children: <Widget>[
Container(),
Positioned(
bottom: 90,
child: Container(
width: MediaQuery.of(context).size.width,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => Home(),
),
);
},
child: Container(
margin: EdgeInsets.symmetric(horizontal: 80),
height: 80,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: mainColor,
),
child: Center(
child: Text(
'Entrar',
style: TextStyle(
fontSize: 25,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
),
Positioned(
bottom: 230,
child: Container(
width: MediaQuery.of(context).size.width,
child: Text(
'Tu mundo 4x4\n empieza aqui!',
style: GoogleFonts.amiri(
height: 1.2,
textStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 40,
),
),
textAlign: TextAlign.center,
),
),
),
],
),
),
),
);
}
}
Once my splash page loads and the button is tapped I want it to now go inside and load this, which is what I had working seperately but with the main.dart pointing to the "nav.dart"
Not sure what you are trying to achieve exactly but you should use the routes or onGenerateRoute in MaterialApp to define your routes.
In that case you can get rid of the home and set the initial route to Splash Screen and the default as nav.
You can then navigate to your tab component using a named route defined in your routes or onGenerateRoute.

How to show the fetched data from api on a button click in flutter?

I want to show the fetched love calculator data after button click but how to visible it? Please answer
import 'dart:io';
import 'package:AllInOneCalci/CustomTextField.dart';
import 'package:AllInOneCalci/Post.dart';
import 'package:AllInOneCalci/customAppBar.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
class LoveCalUI extends StatelessWidget {
#override
Widget build(BuildContext context) {
var AppBarHeight = MediaQuery.of(context).size.height;
return Scaffold(
appBar: customAppBar(
height: (AppBarHeight / 3) * 0.4,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(top: 18.0),
child: Text(
'All In One Cali',
style: TextStyle(
color: Colors.black,
fontSize: 35.0,
fontFamily: 'DancingScript',
fontWeight: FontWeight.bold),
),
),
],
),
),
body: CustomFetchData(),
);
}
}
class CustomFetchData extends StatefulWidget {
#override
_CustomFetchDataState createState() => _CustomFetchDataState();
}
class _CustomFetchDataState extends State<CustomFetchData> {
TextEditingController firstNameController = new TextEditingController();
TextEditingController secondNameController = new TextEditingController();
Future<Post> getData() async {
final response = await http.get(
'https://love-calculator.p.rapidapi.com/getPercentage?fname=aalia&sname=Alice',
headers: {
'x-rapidapi-host': 'love-calculator.p.rapidapi.com',
'x-rapidapi-key':
'84e84770b9msh59a96d8b03cb4aap1615a1jsn1cd0ef******',
});
if (response.statusCode == 200) {
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load api');
}
}
Widget ErrorDesign() {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
alignment: Alignment.center,
child: Text(
'Error: Kindly Connect to Internet',
style: TextStyle(
color: Colors.redAccent,
fontFamily: 'DancingScript',
fontSize: 40.0,
fontWeight: FontWeight.bold,
),
),
),
);
}
Widget DisplayData(String percentageValue, String result) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
height: 100.0,
color: Colors.black,
child: Column(
children: [
Text('Percentage is $percentageValue',
style: TextStyle(
color: Colors.white,
)),
Text('Result is: $result',
style: TextStyle(
color: Colors.white,
)),
],
),
),
);
}
Widget FetchedCalculationValues() {
return Column(
children: [
Container(
child: FutureBuilder<Post>(
future: getData(),
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: CircularProgressIndicator(),
),
);
} else {
if (snapshot.hasError) {
return Container(
child: ErrorDesign(),
);
} else {
return DisplayData(
snapshot.data.percentage, snapshot.data.result);
}
}
})),
],
);
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 18.0, right: 18.0, top: 15.0),
child: CustomTextField('First Name', "", Colors.cyan,
Colors.cyanAccent, Colors.redAccent, firstNameController),
),
Padding(
padding: const EdgeInsets.only(left: 18.0, right: 18.0),
child: CustomTextField('Second Name', "", Colors.red,
Colors.redAccent, Colors.cyanAccent, secondNameController),
),
Padding(
padding: const EdgeInsets.all(18.0),
child: MaterialButton(
color: Colors.redAccent,
child: Text(
'Result',
style: TextStyle(
color: Colors.white,
),
),
onPressed: () {
FetchedCalculationValues();
print('Fetch Calling');
}),
),
Visibility(
visible: false,
child: FetchedCalculationValues(),
),
],
);
}
#override
// ignore: must_call_super
void initState() {
getData();
}
}
How to make the function for api call visible to the screen after button click.
Also I want to use the text field's values at the place of defalut values
Can you solve my problem? It will be very helpful if you do so. I am a newbie and learning flutter since 15 days. Help me so that I can learn it fast. Also the flutter's community is growing fast so it will be easy for me not to wait for response. Thank You.
I have created simplified, single-screen, app without any extra capabilities to solve exactly your issue. It contains two text fields, two Text widgets to display API results and a floating action button to make request.
Key concepts that you should know to make this code are http requests and asynchronous coding. Those links are good starting points for you to get a sense of what actually happens
To summarize what exactly you need:
You send request asynchronously to the API declaring function with async keyword and await keyword in front of http.get() function. This allows you to wait for the result of the request without freezing the app
When result comes back, the rest of the _getNames() function gets executed, which includes setState(). setState() rebuilds your widget and updates values in Text() widgets
Full code:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
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> {
int percentage = 0;
String resultString = "";
Map<String, String> requestHeaders = {
'x-rapidapi-host': 'love-calculator.p.rapidapi.com',
'x-rapidapi-key': 'your API key',
};
final name1Controller = TextEditingController();
final name2Controller = TextEditingController();
void _getNames({String name1, String name2}) async {
final response = await http.get(
'https://love-calculator.p.rapidapi.com/getPercentage?fname=$name1&sname=$name2',
// Send authorization headers to the backend.
headers: requestHeaders,
);
final responseJson = json.decode(response.body);
setState(() {
percentage = int.parse(responseJson['percentage']);
resultString = responseJson['result'];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: name1Controller,
decoration: InputDecoration(
hintText: "name 1",
),
),
TextField(
controller: name2Controller,
decoration: InputDecoration(
hintText: "name 2",
),
),
SizedBox(
height: 10,
),
Text(
'Your Score is: $percentage',
),
Text(
'$resultString',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_getNames(
name1: name1Controller.text,
name2: name2Controller.text,
);
},
tooltip: 'Increment',
child: Text('Go'),
),
);
}
}

Flutter in Native Android App, back pressed not working

I read a lot of topics about that but nothing works and was really same context that mine.
I'm trying to add flutter views inside native Android project, I've got a native Activity which launch a flutter fragment. This flutter fragment contains 2 views (firstScreen and secondScreen). FirstScreen redirect to SecondScreen on button pressed and secondScreen pop back to first screen on button pressed. Until now everything is ok.
But when I'm on second screen I'd like to go back on firstScreen on device back button pressed but instead flutter Fragment is closed and I'm back on native Activity.
The back process looks good as it works when I run flutter module alone.
Here are some screenshots:
And here are some code:
In native MainActivity
override fun startFlutterModule() {
val newFlutterFragment: FlutterFragment = FlutterFragment.createDefault()
supportFragmentManager.beginTransaction()
.replace(
fragmentContainerId,
newFlutterFragment,
TAG_FLUTTER_FRAGMENT
)
.addToBackStack(TAG_FLUTTER_FRAGMENT)
.commit()
}
Base Flutter App
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
routes: {
'/first': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
},
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FirstScreen(),
);
}
}
First Flutter Screen
class FirstScreen extends StatefulWidget {
#override
_FirstScreenState createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"First Screen",
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.w600,
),
),
Padding(
padding: EdgeInsets.all(10.0),
child: RaisedButton(
padding: EdgeInsets.symmetric(
horizontal: 20.0,
vertical: 10.0,
),
onPressed: (){
Navigator.pushNamed(context, '/second');
},
child: Text(
"Screen 2",
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
),
)
],
),
),
);
}
}
Second Flutter Screen
class SecondScreen extends StatefulWidget {
#override
_SecondScreenState createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
#override
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: () async {
Navigator.pop(context);
return Future.value(false);
},
child: Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Second Screen",
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.w600,
),
),
Padding(
padding: EdgeInsets.all(10.0),
child: RaisedButton(
padding: EdgeInsets.symmetric(
horizontal: 20.0,
vertical: 10.0,
),
onPressed: () {
Navigator.pop(context);
},
child: Text(
"Screen 1",
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
),
)
],
),
),
)
);
}
}
From your native activity invoke the onBackPressed() method of the FlutterFragment.
override fun onBackPressed() {
_flutterFragment.onBackPressed()
}
Set true for this attribute when using FlutterFragment, if not, the default hardware back press (or WillPopScope) on dart code will not work.

Overlapping card effect in Flutter

How can I create an overlapping card effect in a SliverAppBar as shown in the figure:
I tried following this article of Medium but the problem is it uses Stack with
Stack{
...
overflow: Overflow.visible,
...
}
to implement this and in Stack, overflowing part of widgets don't take inputs thus making my TabBar half Dead.
What can I do to avoid this?
Full Code
import 'package:flutter/material.dart';
Future<void> main() async {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MenuList(),
);
}
}
class MenuList extends StatefulWidget {
#override
_MenuListState createState() => _MenuListState();
}
class _MenuListState extends State<MenuList> {
static const double _appBarBottomBtnPosition =
24.0; //change this value to position your button vertically
#override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: Text(
'Testing',
style: TextStyle(color: Colors.red),
),
),
SliverAppBar(
pinned: true,
expandedHeight: 200.0,
flexibleSpace: FlexibleSpaceBar(
centerTitle: true,
titlePadding: EdgeInsets.only(bottom: 25),
title: Text('Title'),
),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(0.0),
child: Transform.translate(
offset: const Offset(0, _appBarBottomBtnPosition),
child: RaisedButton(
shape: StadiumBorder(),
child: Text("Click Here"),
onPressed: () {},
),
),
),
),
SliverPadding(
padding: EdgeInsets.only(top: _appBarBottomBtnPosition),
),
SliverFixedExtentList(
itemExtent: 50,
delegate: SliverChildBuilderDelegate(
(context, index){
Color color = Colors.red.withOpacity(1- (index%10)/10);
return Container(
color: color,
alignment: Alignment.center,
child: Text("Color: $color"),
);
}
),
),
],
),
);
}
}

Flutter : change position of text on the appbar

How can i change the position of my text "Sito Web" on the right of the appbar? I tryid with
alignment: Alignment.TopRight
but he move it the text on the top right corner down the appbar. Here a screen of what i mean https://ibb.co/X28TzNN change the position of "Sito Web" in the position of the red cirle. That's the codes, i tryid with this method too, but can't move in the appbar. Here the file with the appbar background_image_task-9.dart
import 'package:flutter/material.dart';
class BackgroundImage extends StatelessWidget{
final Widget body;
BackgroundImage({this.body});
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
elevation: 0,
title: Text('Blumax', style: TextStyle(
fontWeight: FontWeight.w500,
fontFamily: 'DancingScript',
fontSize: 40
),),
centerTitle: false,
),
body: Stack(
children: <Widget>[Container(
decoration: BoxDecoration(
image: DecorationImage(image: AssetImage("assets/blumax.jpg"), fit: BoxFit.cover),
),
),
body
]
)
);
}
}
And here the file with the container hyperlink.dart
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class Hyperlink extends StatelessWidget {
final String _url;
final String _text;
Hyperlink(this._url, this._text);
_launchURL() async {
if (await canLaunch(_url)) {
await launch(_url);
} else {
throw 'Could not launch $_url';
}
}
#override
Widget build(BuildContext context) {
return InkWell(
child: Container(
alignment: Alignment(0.9, -1.0),
child: Text(
_text,
textAlign: TextAlign.right,
style: TextStyle(
fontFamily: 'RobotoMono',
fontSize: 20,
color: Colors.white,
decoration: TextDecoration.underline),
)),
onTap: _launchURL,
);
}
}
main.dart
import 'package:flutter/material.dart';
import 'background_image_task-9.dart';
import 'hyperlink.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Blumax',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: myColour
),
home: BackgroundImage(
body: Center(
child: Hyperlink('www.test.it', 'Sito Web',),
),
)
);
}
}
You can use Row widget and use mainAxisAlignment: MainAxisAlignment.spaceBetween to render BluMax and Sito Web elements on left and right of the appbar respectively. And since you want to open a url after tapping on sito web, you can wrap that element with GestureDetector and then call launchURL method that opens required url. A working sample code is as below:
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Blumax'),
GestureDetector(
child: Text('Sito Web'),
onTap: _openURL
)
],
),
centerTitle: false,
actions: <Widget>[
PopupMenuButton<int>(
itemBuilder: (context) =>
[
PopupMenuItem(
value: 1,
child: Text("First"),
),
PopupMenuItem(
value: 2,
child: Text("Second"),
),
],
)
],
),
This is rendered on screen as:
...
void _openURL() async {
const url = 'https://flutter.dev';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
I just used a text Blumax for demo, but you may replace it per your need.
Hope this answers your question.

Categories

Resources