good evening. I’m trying to assign a Shared Preference url but the page doesn’t load, it only works when I assign the value to a variable like this:
String url = 'https://www.youtube.com/';
I have tried in many ways and I still have not been able to find out where I have the error, I am new to the world of flutter I hope you can help me.
This is the code…
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Webpage extends StatefulWidget {
const Webpage({super.key});
@override
State<Webpage> createState() => _WebpageState();
}
class _WebpageState extends State<Webpage> {
String initialUrl = '';
@override
void initState() {
super.initState();
main();
}
String miStringGlobal = '';
Future<void> obtenerValorPrefCompartida() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
miStringGlobal = prefs.getString('link') ?? "https://www.google.com";
}
void main() async {
await obtenerValorPrefCompartida();
}
double _progress = 0;
late InAppWebViewController webView;
GlobalKey<ScaffoldState> ScaffoldKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: ScaffoldKey,
appBar: AppBar(
backgroundColor: Color(0xff041f40),
elevation: 0,
centerTitle: true,
title: Text(
"TEST",
style: TextStyle(color: const Color.fromARGB(255, 255, 255, 255)),
),
),
body: Stack(
children: [
InAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse(miStringGlobal)),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onProgressChanged:
(InAppWebViewController controller, int progress) {
setState(() {
_progress = progress / 100;
});
},
),
_progress < 1
? SizedBox(
height: 3,
child: LinearProgressIndicator(
value: _progress,
backgroundColor: Colors.red.withOpacity(0.2),
),
)
: SizedBox()
],
),
);
}
}
I attach the code and I would like you to tell me where my error can be.
2
Answers
You need to call
setState()
when you changemiStringGlobal
value to update UIUpdate your function
obtenerValorPrefCompartida
to:Try to change inti var miStringGlobal
from this
String miStringGlobal = '';
to this
String miStringGlobal = "https://www.google.com";
if its load google then the problem is your widget is start to build before init, in that case
add some loading flag