Inappwebview and Shared Preference URL I can't assign the url stored in Shared Preference

huangapple go评论63阅读模式
英文:

Inappwebview and Shared Preference URL I can't assign the url stored in Shared Preference

问题

I have reviewed the provided code. Based on the information you provided, it seems you are trying to load a URL from Shared Preferences in a Flutter app, but the page doesn't load. The issue might be with how you are retrieving and using the URL from Shared Preferences.

Ensure that you have the necessary permissions to access the internet in your AndroidManifest.xml file if you are testing on an Android device.

Additionally, make sure that the value you are getting from Shared Preferences is a valid URL. You can add some debugging statements to check the value of miStringGlobal after retrieving it from Shared Preferences to ensure it contains a valid URL.

If the issue persists, you might want to check if there are any errors or logs in the console when running the app, as they can provide more specific information about what might be going wrong.

英文:

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.

答案1

得分: 0

请注意调用setState(),当您更改miStringGlobal的值以更新UI。

更新您的函数obtenerValorPrefCompartida如下:

Future<void> obtenerValorPrefCompartida() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  setState(() {
    miStringGlobal = prefs.getString('link') ?? "https://www.google.com";
  });
}

如果您需要进一步的帮助,请告诉我。

英文:

You need to call setState() when you change miStringGlobal value to update UI

Update your function obtenerValorPrefCompartida to:

  Future&lt;void&gt; obtenerValorPrefCompartida() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      miStringGlobal = prefs.getString(&#39;link&#39;) ?? &quot;https://www.google.com&quot;;
    }); 
  }

答案2

得分: 0

尝试将代码中的以下部分从:

String miStringGlobal = &#39;&#39;;

更改为:

String miStringGlobal = &quot;https://www.google.com&quot;;

如果加载 Google 成功,那么问题可能是你的小部件在初始化之前开始构建。在这种情况下,添加一些加载标志:

bool isloading = false;

这是你代码中需要翻译的部分。

英文:

Try to change inti var miStringGlobal

from this String miStringGlobal = &#39;&#39;;
to this String miStringGlobal = &quot;https://www.google.com&quot;;

if its load google then the problem is your widget is start to build before init, in that case

add some loading flag

import &#39;package:flutter/material.dart&#39;;
import &#39;package:flutter_inappwebview/flutter_inappwebview.dart&#39;;
import &#39;package:shared_preferences/shared_preferences.dart&#39;;

class Webpage extends StatefulWidget {
 const Webpage({super.key});
 @override
 State&lt;Webpage&gt; createState() =&gt; _WebpageState();
}

class _WebpageState extends State&lt;Webpage&gt; {
String initialUrl = &#39;&#39;;
bool isloading=false;


 @override
 void initState() {
  super.initState();
  isloading=true;
  main();
  }

  String miStringGlobal = &#39;&#39;;

 Future&lt;void&gt; obtenerValorPrefCompartida() async {
 SharedPreferences prefs = await SharedPreferences.getInstance();
 miStringGlobal = prefs.getString(&#39;link&#39;) ?? &quot;https://www.google.com&quot;;
 setState(() {
   isloading=false;
  });
 }

  void main() async {
   await obtenerValorPrefCompartida();    
  
  }

 double _progress = 0;
 late InAppWebViewController webView;
 GlobalKey&lt;ScaffoldState&gt; ScaffoldKey = GlobalKey&lt;ScaffoldState&gt;();

 @override
 Widget build(BuildContext context) {
  return Scaffold(
  key: ScaffoldKey,
  appBar: AppBar(
    backgroundColor: Color(0xff041f40),
    elevation: 0,
    centerTitle: true,
    title: Text(
      &quot;TEST&quot;,
      style: TextStyle(color: const Color.fromARGB(255, 255, 255, 255)),
    ),
  ),
  body:isloading?Text(&quot;loading&quot;): Stack(
    children: [
      InAppWebView(
        initialUrlRequest: URLRequest(url: Uri.parse(miStringGlobal)),
        onWebViewCreated: (InAppWebViewController controller) {
          webView = controller;
        },
        onProgressChanged:
            (InAppWebViewController controller, int progress) {
          setState(() {
            _progress = progress / 100;
          });
        },
      ),
      _progress &lt; 1
          ? SizedBox(
              height: 3,
              child: LinearProgressIndicator(
                value: _progress,
                backgroundColor: Colors.red.withOpacity(0.2),
              ),
            )
          : SizedBox()
    ],
  ),
);
}
}

huangapple
  • 本文由 发表于 2023年5月11日 15:46:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定